package com.dj.dormitory.commonutils;

import com.dj.dormitory.entity.User;
import com.dj.dormitory.entity.vo.SignVo;
import io.jsonwebtoken.*;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * @Author DJ同学
 * @Date 2021/1/25 9:19
 * @Version 1.0
 */
public class JWTUtil {

    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    //生成签名
    public static String getJwtToken(SignVo signVo){

        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject(signVo.getUserName())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("userId", signVo.getUserId())
                .claim("userName", signVo.getUserName())
                .claim("type", signVo.getType())
                .claim("studentId",signVo.getStudentId())
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
        return JwtToken;
    }


    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if(StringUtils.isEmpty(jwtToken)) return false;
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * @param request
     * @return
     */
    public static SignVo getSignByToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
        if(StringUtils.isEmpty(jwtToken)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        SignVo signVo = new SignVo();
        signVo.setUserId((Integer) claims.get("userId"));
        signVo.setUserName((String) claims.get("userName"));
        signVo.setType((Integer) claims.get("type"));
        signVo.setStudentId((Integer) claims.get("studentId"));
        return signVo;
    }
}
